<template >
    <section id="cicd-deployflows">


        <el-row>

            <el-col :span="24"  style="padding-bottom: 0px;width: 90%">
                <el-form :inline="true" :model="filters" size="small">
                    <el-form-item>
                        <el-input v-model="filters.itemid" placeholder="任务ID"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="mini">查询</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="default" @click="linkToAddDeployflow" size="mini">新增 </el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
        <!--新增任务-->

        <el-row style="padding-bottom: 0px;width: 90%">
        <!--列表-->
            <el-col :span="8">
                <el-table
                        ref="restTable"
                        :data="jobsData.slice((currpage - 1) * pagesize, currpage * pagesize)"
                        style="width: 100%"
                        :row-style='rowStyle'
                        highlight-current-row
                        @current-change="handleCurrentChange"
                        border
                        :default-sort = "{prop: 'id', order: 'descending'}"
                >
                    <el-table-column
                            prop="id"
                            label="id"
                            sortable
                            width="60">
                    </el-table-column>
                    <el-table-column
                            prop="status"
                            label="状态"
                            width="80"
                            :filters="[{text: '已结束', value: '2'}, {text: '已中止', value: '1'}, {text: '未执行', value: '0'}]"
                            :filter-method="filterStatus"
                    >
                        <template slot-scope="scope">
                            <!--<el-tag :type="scope.row.laststatus=='成功'? 'success': 'danger'"  :style="scope.row.laststatus=='成功'? 'color:green': 'color:red'" size="mini">{{ scope.row.laststatus }}</el-tag>-->
                            <div v-if="scope.row.status==='0'">
                                <el-tag type="default" size="mini">未执行</el-tag>
                            </div>
                            <div v-else-if="scope.row.status==='1'">
                                <!--<el-tag type="danger"  size="mini"> {{scope.row.laststatus}} </el-tag>-->
                                <el-tag type="info" size="mini">已中止</el-tag>
                            </div>
                            <div v-else>
                                <el-tag type="warning" size="mini">已结束</el-tag>
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column
                            prop="title"
                            label="上线任务标题"

                            fit
                            >
                    </el-table-column>
                    <el-table-column
                            prop="createtime"
                            label="创建时间"
                            width="160"

                    >
                    </el-table-column>

                </el-table>
                <el-pagination
                        style="float: right;"
                        small
                        layout="prev, pager, next, sizes, total"
                        :pager-count="5"
                        :page-sizes="[5, 10, 15, 20,50]"
                        :page-size="pagesize"
                        :total="jobsData.length"
                        @current-change="handlePageCurrentChange"
                        @size-change="handleSizeChange"
                        :hide-on-single-page="true"
                >
                </el-pagination>
            </el-col>

            <el-col :span="16" >

                <div class="block" id="watermark-timeline">

                    <el-timeline  >

                        <el-timeline-item

                                :icon="jobtimeline.title.icon"
                                :type="jobtimeline.title.type"
                                :color="jobtimeline.title.color"
                                :size="jobtimeline.title.size"
                                :timestamp="jobtimeline.title.timestamp"
                                placement="top"
                        >
                            <el-card class="watermarkTimeline bg-card">
                                <el-tag  type="danger" style="margin-left: 25px">{{jobtimeline.title.title}}</el-tag>


                            </el-card>

                        </el-timeline-item>

                        <el-timeline-item

                                :icon="jobtimeline.content.icon"
                                :type="jobtimeline.content.type"
                                :color="jobtimeline.content.color"
                                :size="jobtimeline.content.size"
                                :timestamp="jobtimeline.content.timestamp"
                                placement="top"
                        >
                            <el-card class="bg-card">

                                    <div v-for="c in jobtimeline.content.content.split('\n')" style="margin-left: 20px">{{c}}</div>

                            </el-card>

                        </el-timeline-item>

                        <el-timeline-item

                                :icon="jobtimeline.process.icon"
                                :type="jobtimeline.process.type"
                                :color="jobtimeline.process.color"
                                :size="jobtimeline.process.size"
                                :timestamp="jobtimeline.process.timestamp"
                                placement="top"
                        >
                            <el-card class="bg-card">
                                <ol>
                                    <li>依次执行sql脚本以及项目</li>
                                    <li>默认当中某个任务执行失败会终止整个发布流程</li>
                                    <li>当任务执行到一半被终止或者遇错时，联系运维人员手动执行未执行和失败的任务</li>
                                </ol>
                            </el-card>
                        </el-timeline-item>

                        <!--测试报告-->
                        <el-timeline-item

                                :icon="jobtimeline.report.icon"
                                :type="jobtimeline.report.type"
                                :color="jobtimeline.report.color"
                                :size="jobtimeline.report.size"
                                :timestamp="jobtimeline.report.timestamp"
                                placement="top"
                        >
                            <el-card class="watermarkTimeline bg-card">
                                <el-button type="text"  icon="el-icon-download" style="margin-left: 25px" @click="downloadTestReport(jobtimeline.report.filepath,jobtimeline.report.filename)">{{jobtimeline.report.filename}}</el-button>
                            </el-card>

                        </el-timeline-item>

                        <!--脚本任务-->
                        <el-timeline-item
                                v-if="jobtimeline.jobscript.dblist.length >0 && jobtimeline.jobscript.dblist[0] !== '' &&jobtimeline.jobscript.dblist !== undefined"
                                :icon="jobtimeline.jobscript.icon"
                                :type="jobtimeline.jobscript.type"
                                :color="jobtimeline.jobscript.color"
                                :size="jobtimeline.jobscript.size"
                                :timestamp="jobtimeline.jobscript.timestamp"
                                placement="top"
                        >
                            <el-card class="bg-card"
                                     v-loading="jobProgressData[currentJobid].sqlloading !== undefined ? jobProgressData[currentJobid].sqlloading : 'false'"
                                     element-loading-text="玩命执行中"
                                     element-loading-spinner="el-icon-loading"
                                     element-loading-background="rgba(0, 0, 0, 0.8)"
                            >

                                <div v-for="(db,index) in jobtimeline.jobscript.dblist">
                                    <el-tag size="small"><i class="iconfont" style="font-weight: bold;">&#xe69b;</i> {{db}}</el-tag>
                                    <ol>
                                        <li v-for="sql in jobtimeline.jobscript.sqlpath[index].split(';')" style="font-size: 15px ; margin-bottom: 3px">
                                            <!--一个db规定只对应一个sql脚本-->
                                            <!--<el-tag type="danger" size="mini" style="margin-right: 5px"><i class="el-icon-more-outline"></i></el-tag>-->
                                            <el-tooltip class="item" effect="light" :content="jobProgressData[currentJobid].dbjob[db].result" placement="bottom-start">
                                            <el-button class="minizisesize" round  plain :type="jobProgressData[currentJobid].dbjob[db].type" :icon="jobProgressData[currentJobid].dbjob[db].icon" size="mini" ></el-button>
                                            </el-tooltip>
                                            {{sql.split("/")[sql.split("/").length - 1]}}&nbsp;&nbsp;&nbsp;&nbsp;
                                            <el-button-group>
                                                <el-button type="primary" size="mini" icon="el-icon-reading" @click="previewSqlFile(db,sql)" ></el-button>
                                                <!--sql 文件预览-->
                                                <el-dialog title="脚本内容" :visible.sync="dialogSqlVisible">
                                                    <el-input
                                                            type="textarea"
                                                            readonly
                                                            :autosize="{ minRows: 1, maxRows: 20}"
                                                            v-model="sqlFileContent">
                                                    </el-input>
                                                </el-dialog>


                                                <el-button type="success" size="mini" icon="el-icon-download" @click="downloadSqlFile(db,sql)"></el-button>
                                                <el-button type="warning" size="mini" icon="el-icon-video-play" @click="runScriptByhand(db,sql) " :disabled="jobProgressData[currentJobid].dbjob[db].button" v-if="execdisabled"></el-button>
                                            </el-button-group>
                                        </li>
                                    </ol>
                                </div>
                            </el-card>

                        </el-timeline-item>


                        <!--项目发布-->
                        <el-timeline-item
                                v-if="jobtimeline.jobitems.items.length >0 && jobtimeline.jobitems.items[0] !== '' && jobtimeline.jobitems.items !== undefined"
                                :icon="jobtimeline.jobitems.icon"
                                :type="jobtimeline.jobitems.type"
                                :color="jobtimeline.jobitems.color"
                                :size="jobtimeline.jobitems.size"
                                :timestamp="jobtimeline.jobitems.timestamp"
                                placement="top"
                        >
                            <el-card
                                    class="bg-card"
                                    v-loading="jobProgressData[currentJobid].itemloading"
                                    element-loading-text="玩命执行中"
                                    element-loading-spinner="el-icon-loading"
                                    element-loading-background="rgba(0, 0, 0, 0.8)"
                            >

                                <div v-for="item in jobtimeline.jobitems.items " style="margin-bottom: 5px">
                                    <!--<el-tag type="danger" size="mini" ><i class="el-icon-more-outline"></i></el-tag>-->
                                    <el-tooltip class="item" effect="light" :content="jobProgressData[currentJobid].itemjob[item].result" placement="bottom-start">
                                    <el-button class="minizisesize" round plain :type="jobProgressData[currentJobid].itemjob[item].type" :icon="jobProgressData[currentJobid].itemjob[item].icon"  size="mini"  @click="linkToAddItemWorkspace(jobProgressData[currentJobid].itemjob[item].result,item)" ></el-button>
                                    </el-tooltip>
                                    <el-tag  style="margin-right: 5px" size="small" >{{item}}</el-tag>
                                    <el-button icon="el-icon-caret-right" type="warning" circle plain size="mini" @click="runDeployItemByhand(item) " :disabled="jobProgressData[currentJobid].itemjob[item].button" v-if="execdisabled"></el-button>
                                </div>
                            </el-card>

                        </el-timeline-item>

                        <el-timeline-item
                                :icon="jobtimeline.handel.icon"
                                :type="jobtimeline.handel.type"
                                :color="jobtimeline.handel.color"
                                :size="jobtimeline.handel.size"
                                :timestamp="jobtimeline.handel.timestamp"
                                placement="top"
                        >
                            <el-card class="bg-card">
                                <el-row>
                                    <el-button :type="startButton.type" :disabled="startButton.ifclick" @click="beginDeployJob" size="mini">{{startButton.content}}</el-button>
                                    <el-button :type="doneButton.type" :disabled="doneButton.ifclick"  @click="handelDone" size="mini">{{doneButton.content}}</el-button>
                                    <!--<el-button type="warning">终止</el-button>-->
                                    <el-button type="danger" :disabled="deleteButton.ifclick" size="mini" @click="handelDeleteJob">删除</el-button>
                                </el-row>
                            </el-card>
                        </el-timeline-item>


                    </el-timeline>

                </div>


            </el-col>
        </el-row>
    </section>
</template>



<script>
    import { getDeployJobs,GetDeploymentJobStatus,StartDeployJob,CloseDeploymentJobStatus,GetFileSize,LoadTemplateFile,StartDeploySqlJobByhand,StartDeployItemJobByhand,DeleteDeployJob } from '../../api/api'
    import $ from 'jquery' //添加水印
    import watermark from '../../assets/js/jquery.watermark'

    import VJstree from 'vue-jstree'
    import saveAs from 'file-saver';
    var FileSaver = require('file-saver');

    export default {
        data() {
            return {
                filters: {
                    itemid: ''
                },
                jobsData: [],

                //分页
                pagesize: 10,
                currpage: 1,

                jobtimeline: {
                    title : {
                        title: "测试-标题",
                        timestamp: '上线标题',
                        size: 'large',
                        type: 'primary',
                        icon: 'el-icon-s-flag',
                    },
                    content: {
                        content: "测试  - 修复BUG",
                        timestamp: '上线内容',
                        size: 'large',
                        type: 'primary',
                        icon: 'el-icon-tickets',
                    },
                    report: {
                        filename: "测试报告",
                        filepath: "",

                        timestamp: '测试报告',
                        size: 'large',
                        type: 'success ',
                        icon: 'el-icon-finished',
                    },
                    jobscript: {
                        timestamp: '上线脚本',
                        size: 'large',
                        type: 'danger',
                        icon: 'el-icon-cpu',
                        dblist: [""],
                        sqlpath: [""],
                    },
                    jobitems: {
                        timestamp: '上线项目',
                        size: 'large',
                        type: 'danger',
                        icon: 'el-icon-cpu',
                        items: [""]
                    },
                    process: {
                        timestamp: '发布流程--依次执行',
                        size: 'large',
                        type: 'primary',
                        icon: 'el-icon-s-comment',
                    },
                    handel: {
                        size: 'large',
                        type: 'primary',
                        icon: 'el-icon-thumb',
                    },


                },
                currentJobid: 10000,    //用于展示任务进度
                deploymentJobid: null, //用于开始执行任务的id传值
                execdisabled: true,
                loading: false,
                jobProgressData: {
                    //非结构化存储
                    //默认设定
                    10000: {
                        "sqlloading": true,
                        "dbjob" : {},
                        "itemloading":true,
                        "itemjob": {

                        },
                    },
                },
                jobstatustimer: null,
                startButton: {
                    type: "primary",
                    content: "开始",
                    ifclick: true,
                },
                doneButton: {
                    type: "success",
                    content: "关闭",
                    ifclick: true,
                },
                deleteButton: {
                    ifclick: true,
                },

                dialogSqlVisible: false, //预览sql
                sqlFileContent: "",
            }
        },
        methods: {
            rowStyle({ row, rowIndex}) {
                return 'height:30'
            },
            setCurrent(row) {
                this.$refs.restTable.setCurrentRow(row);
            },
            getAllDeployJobs(){
                console.log("debug")
                getDeployJobs().then((res) => {

                    console.log(res.data.jobs)
                    this.jobsData = res.data.jobs
                    this.setCurrent(this.jobsData[0])    //默认选中第一行
                    //this.ipALL = res.data.iplists
                    }
                )
            },
            getDeployJobStatusById(thisid){
                let param = {id:thisid}
                GetDeploymentJobStatus(param).then((res) => {
                    console.log(JSON.parse(res.status))
                    //this.deploymentItems = res.data.items
                    //this.jobProgressData[this.currentJobid] = res.status
                    this.jobProgressData[this.currentJobid] = JSON.parse(res.status)
                })


            },

            setTimer(id) {
                if(this.jobstatustimer == null) {
                    this.jobstatustimer = setInterval( () => {
                        this.getDeployJobStatusById(id)
                    }, 300000)
                }
            },

            handleCurrentChange(val) {
                //设置开始键盘
                this.deleteButton.ifclick = false
                if (val.status === '0') {
                    this.startButton.type = "primary"
                    this.startButton.content = "开始"
                    this.startButton.ifclick = false

                    this.execdisabled = true

                    this.doneButton.type = "success"
                    this.doneButton.content = "关闭"
                    this.doneButton.ifclick = true
                    $("#watermark-timeline").watermark({
                        texts : ["未开始"], //水印文字
                        textColor : "#d2d2d2", //文字颜色
                        textFont : '14px 微软雅黑', //字体
                        width : 460, //水印文字的水平间距
                        height : 200,  //水印文字的高度间距（低于文字高度会被替代）
                        textRotate : -30 //-90到0， 负数值，不包含-90
                    })



                }else if(val.status === '1' )  {
                    this.startButton.type = "info"
                    this.startButton.content = "开始"
                    this.startButton.ifclick = true

                    this.doneButton.type = "success"
                    this.doneButton.content = "关闭"
                    this.doneButton.ifclick = false

                    this.execdisabled = true

                    //添加水印
                    $("#watermark-timeline").watermark({
                        texts : ["失败", "失败", "失败"], //水印文字
                        textColor : "#d2d2d2", //文字颜色
                        textFont : '14px 微软雅黑', //字体
                        width : 460, //水印文字的水平间距
                        height : 200,  //水印文字的高度间距（低于文字高度会被替代）
                        textRotate : -30 //-90到0， 负数值，不包含-90
                    })



                } else if(val.status === '2' ) {
                    this.startButton.type = "warning"
                    this.startButton.content = "重启"
                    this.startButton.ifclick = false

                    this.doneButton.type = "success"
                    this.doneButton.content = "关闭"
                    this.doneButton.ifclick = true


                    this.execdisabled = false    //任务结束后不可以手动执行

                    $("#watermark-timeline").watermark({
                        texts : ["结束", "结束", "结束"], //水印文字
                        textColor : "#d2d2d2", //文字颜色
                        textFont : '14px 微软雅黑', //字体
                        width : 460, //水印文字的水平间距
                        height : 200,  //水印文字的高度间距（低于文字高度会被替代）
                        textRotate : -30, //-90到0， 负数值，不包含-90
                        zIndex: 100,
                    })
                }


                this.deploymentJobid = val.id
                //点击马上进行赋值
                let param = {id:val.id}
                GetDeploymentJobStatus(param).then((res) => {
                    console.log(JSON.parse(res.status))
                    //this.deploymentItems = res.data.items
                    //this.jobProgressData[this.currentJobid] = res.status
                    this.jobProgressData[this.currentJobid] = JSON.parse(res.status)
                })




                //清楚定时器
                clearInterval(this.jobstatustimer)
                this.jobstatustimer = null

                //console.log("val is " , val)
                console.log(val.content.split("\n"))

                let self = this
                //self.currentJobid = val.id
                console.log("currendjobid is" , self.currentJobid)
                //设置标题
                self.jobtimeline.title.title = val.title

                //测试报告
                self.jobtimeline.report.filepath = val.reportFilepath

                self.jobtimeline.report.filename = val.reportFilepath.split("/")[val.reportFilepath.split("/").length - 1]

                //设置上线内容
                self.jobtimeline.content.content = val.content
                //设置上线脚本

                    self.jobtimeline.jobscript.dblist = val.dblist.split(" ")
                    self.jobtimeline.jobscript.sqlpath = val.sqlpathlist.split(",")
                    console.log("sqlpath " ,self.jobtimeline.jobscript.sqlpath )

                //设置上线项目
                self.jobtimeline.jobitems.items = val.itemlist.split(" ")


                //开始设置定时器
                console.log(self.currentJobid)
                self.setTimer(val.id)

            },

            previewSqlFile(db,sql){
                //alert(sql)
                let param = {filepath: sql}
                GetFileSize(param).then((res) => {
                    console.log("file size",res.size)
                    if (parseInt(res.size) > 10*1024) {
                        this.$message({
                            message: '文件超过10k，请下载确认',
                            type: 'warning'
                        });
                    } else {
                        //加载文件
                        let sqlpath = "/"+sql
                        LoadTemplateFile(sqlpath).then((res) => {

                            //console.log("sql file is" , res)
                            this.sqlFileContent = res
                            this.dialogSqlVisible = true

                        })

                    }
                })



            },
            downloadSqlFile(db,sql){
                //alert("this: " + db + "   " +  sql)
                let url = "http://127.0.0.1:8088/" + sql
                let filename = db + ".sql"
                FileSaver.saveAs(url,filename)
            },
            downloadTestReport(path,filename){
                //alert("this: " + db + "   " +  sql)
                let url = "http://127.0.0.1:8088/" + path
                FileSaver.saveAs(url,filename)
            },
            runScriptByhand(db,sql){
                //alert("任务流带参数 ， this: " + db + "   " +  sql)
                let param = {dbname:db,sqlpath:sql,id: this.deploymentJobid}  //this.deploymentJobid 并不是sqljob本身的id 而是 deploymentid
                StartDeploySqlJobByhand(param).then((res) => {
                    console.log("start hand run sql script  result",res)
                })
            },
            runDeployItemByhand(item){
                //alert("任务流带参数 ， this: " + db + "   " +  sql)
                let param = {name:item,id: this.deploymentJobid}  //this.deploymentJobid 并不是sqljob本身的id 而是 deploymentid
                StartDeployItemJobByhand(param).then((res) => {
                    console.log("start hand run sql script  result",res)
                })
            },
            handelDone() {
                this.execdisabled = false
                //TODO: set this job status 2  ， 手动关闭任务
                //alert(this.deploymentJobid)
                this.$confirm('关闭此项任务, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let param = {id:this.deploymentJobid}
                    CloseDeploymentJobStatus(param).then((res) => {
                        if (res.code === 200) {
                            this.$message({
                                type: 'success',
                                message: '已关闭!'
                            });
                        }else {
                            this.$message({
                                type: 'warning',
                                message: '关闭失败！'
                            });
                        }

                    })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消关闭'
                    });
                });




            },
            handelDeleteJob() {

                this.$confirm('确认删除此项任务, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'error'
                }).then(() => {
                    let param = {id:this.deploymentJobid}
                    DeleteDeployJob(param).then((res) => {
                        if (res.code === 200) {
                            this.$message({
                                type: 'success',
                                message: '已删除!'
                            });
                        }else if (res.code === 400) {
                            this.$message({
                                type: 'error',
                                message: res.message,
                            });
                        }

                    })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消关闭'
                    });
                });




            },


            beginDeployJob(){
                //执行任务
                //alert(this.deploymentJobid)
                let param = {id: this.deploymentJobid}

                StartDeployJob(param).then((res) => {
                    console.log("start result",res)
                    if (res.code === 400) {
                        this.$message({
                            type: 'error',
                            message: res.message,
                        });
                    }

                })
            },
            linkToAddDeployflow(){
                this.$router.push('/deploy/newjob')
            },
            linkToAddItemWorkspace(output,item){
                // alert()
                let id = output.split("#")[1]
                if (id !== undefined){
                    // alert(id+item)
                    this.$router.push('/deploy/item/' + item + "/" + id + "/output")
                }
                // this.$router.push('/deploy/newjob')
            },

            filterStatus(value, row) {
                return row.status === value;
            },

            handlePageCurrentChange(cpage) {
                this.currpage = cpage;
            },
            handleSizeChange(psize) {
                this.pagesize = psize;
            },

        },
        mounted() {
            this.getAllDeployJobs()

        },
        destroyed: function () {  //单组件页面
            // 每次离开当前界面时，清除定时器
            clearInterval(this.jobstatustimer)
            this.jobstatustimer = null
        }
    }
</script>

<style>
#cicd-deployflows .minizisesize{
    -webkit-transform: scale(0.6) !important;
}
#cicd-deployflows .bg-card {
    background-color: #FAFAFA;
}

</style>